import { Database } from "bun:sqlite";

const db = new Database("projects.db");

export function initDb() {
  console.log("init db");
  db.prepare(
    `CREATE TABLE IF NOT EXISTS "projects" (
        "id"	INTEGER NOT NULL UNIQUE,
        "val"	TEXT,
        PRIMARY KEY("id" AUTOINCREMENT)
    )`
  ).run();
}

export function insertProject(val) {
  return db
    .prepare("INSERT INTO projects (val) VALUES (?)")
    .run(JSON.stringify(val));
}

export function insertManyProjects(projects) {
  return db.transaction((vals) => {
    for (const project of vals) insertProject(project);
  })(projects);
}

export function getProjects() {
  try {
    return db
      .prepare("SELECT id, val FROM projects")
      .all()
      .map((v) => {
        const project = JSON.parse(v.val);
        project.id = v.id;
        return project;
      });
  } catch (error) {
    return [];
  }
}

export function updateProject(id, val) {
  return db
    .prepare("UPDATE projects SET val =? WHERE id =?")
    .run(JSON.stringify(val), id);
}
